<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)">
        <t-form-item label="商铺ID" name="shopId">
          <t-input v-model="queryParams.shopId" placeholder="请输入商铺ID" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="优惠券名称" name="couponName">
          <t-input v-model="queryParams.couponName" placeholder="请输入优惠券名称" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="面额/减免金额" name="value">
          <t-input v-model="queryParams.value" placeholder="请输入面额/减免金额" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="满减条件" name="minSpend">
          <t-input v-model="queryParams.minSpend" placeholder="请输入满减条件" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="有效期开始时间" name="startDate">
          <t-date-picker
            v-model="queryParams.startDate"
            allow-input
            clearable
            placeholder="请选择有效期开始时间"
          />
        </t-form-item>
        <t-form-item label="有效期结束时间" name="endDate">
          <t-date-picker
            v-model="queryParams.endDate"
            allow-input
            clearable
            placeholder="请选择有效期结束时间"
          />
        </t-form-item>
        <t-form-item label="总数量" name="totalQuantity">
          <t-input v-model="queryParams.totalQuantity" placeholder="请输入总数量" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="剩余数量" name="remainingQuantity">
          <t-input v-model="queryParams.remainingQuantity" placeholder="请输入剩余数量" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="使用说明" name="description">
          <t-input v-model="queryParams.description" placeholder="请输入使用说明" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label-width="0px">
          <t-button theme="primary" @click="handleQuery">
            <template #icon> <search-icon /></template>
            搜索
          </t-button>
          <t-button theme="default" @click="resetQuery">
            <template #icon> <refresh-icon /></template>
            重置
          </t-button>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="couponId"
        :data="couponList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['xyyw:coupon:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>
              <t-button
                v-hasPermi="['xyyw:coupon:edit']"
                theme="default"
                variant="outline"
                :disabled="single"
                @click="handleUpdate()"
              >
                <template #icon> <edit-icon /> </template>
                修改
              </t-button>
              <t-button
                v-hasPermi="['xyyw:coupon:remove']"
                theme="danger"
                variant="outline"
                :disabled="multiple"
                @click="handleDelete()"
              >
                <template #icon> <delete-icon /> </template>
                删除
              </t-button>
              <t-button v-hasPermi="['xyyw:coupon:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>
        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <t-link v-hasPermi="['xyyw:coupon:query']" theme="primary" hover="color" @click.stop="handleDetail(row)">
              <browse-icon />详情
            </t-link>
            <t-link v-hasPermi="['xyyw:coupon:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
              <edit-icon />修改
            </t-link>
            <t-link v-hasPermi="['xyyw:coupon:remove']" theme="danger" hover="color" @click.stop="handleDelete(row)">
              <delete-icon />删除
            </t-link>
          </t-space>
        </template>
      </t-table>
    </t-space>

    <!-- 添加或修改优惠券对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="500px"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="couponRef.submit()"
    >
      <t-loading :loading="buttonLoading" size="small">
        <t-form
          ref="couponRef"
          label-align="right"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
        >
          <t-form-item label="商铺ID" name="shopId">
            <t-input-number v-model="form.shopId" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="优惠券名称" name="couponName">
            <t-input v-model="form.couponName" placeholder="请输入优惠券名称" clearable />
          </t-form-item>
          <t-form-item label="面额/减免金额" name="value">
            <t-input-number v-model="form.value" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="满减条件" name="minSpend">
            <t-input-number v-model="form.minSpend" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="有效期开始时间" name="startDate">
            <t-date-picker
              v-model="form.startDate"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择有效期开始时间"
            />
          </t-form-item>
          <t-form-item label="有效期结束时间" name="endDate">
            <t-date-picker
              v-model="form.endDate"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择有效期结束时间"
            />
          </t-form-item>
          <t-form-item label="总数量" name="totalQuantity">
            <t-input-number v-model="form.totalQuantity" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="剩余数量" name="remainingQuantity">
            <t-input-number v-model="form.remainingQuantity" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="使用说明" name="description">
            <t-textarea v-model="form.description" placeholder="请输入使用说明" />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 优惠券详情 -->
    <t-dialog
      v-model:visible="openView"
      header="优惠券详情"
      placement="center"
      width="700px"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">
        <t-descriptions-item label="优惠券ID">{{ form.couponId }}</t-descriptions-item>
        <t-descriptions-item label="商铺ID">{{ form.shopId }}</t-descriptions-item>
        <t-descriptions-item label="优惠券名称">{{ form.couponName }}</t-descriptions-item>
        <t-descriptions-item label="类型">{{ form.type }}</t-descriptions-item>
        <t-descriptions-item label="面额/减免金额">{{ form.value }}</t-descriptions-item>
        <t-descriptions-item label="满减条件">{{ form.minSpend }}</t-descriptions-item>
        <t-descriptions-item label="有效期开始时间">{{ parseTime(form.startDate) }}</t-descriptions-item>
        <t-descriptions-item label="有效期结束时间">{{ parseTime(form.endDate) }}</t-descriptions-item>
        <t-descriptions-item label="总数量">{{ form.totalQuantity }}</t-descriptions-item>
        <t-descriptions-item label="剩余数量">{{ form.remainingQuantity }}</t-descriptions-item>
        <t-descriptions-item label="使用说明" :span="2">{{ form.description }}</t-descriptions-item>
        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>
      </my-descriptions>
    </t-dialog>
  </t-card>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'Coupon',
});
import {
  AddIcon,
  BrowseIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type { FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext,  } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { XyywCouponForm, XyywCouponQuery, XyywCouponVo } from '@/api/xyyw/model/couponModel';
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from '@/api/xyyw/coupon';

const { proxy } = getCurrentInstance();

const openView = ref(false);
const openViewLoading = ref(false);
const couponRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const couponList = ref<XyywCouponVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);

// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({
  shopId: [{ required: true, message: '商铺ID不能为空' }],
  couponName: [{ required: true, message: '优惠券名称不能为空' }],
});

// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
  { title: `商铺ID`, colKey: 'shopId', align: 'center' },
  { title: `优惠券名称`, colKey: 'couponName', align: 'center' },
  { title: `类型`, colKey: 'type', align: 'center' },
  { title: `面额/减免金额`, colKey: 'value', align: 'center' },
  { title: `满减条件`, colKey: 'minSpend', align: 'center' },
  { title: `有效期开始时间`, colKey: 'startDate', align: 'center', minWidth: 112, width: 180 },
  { title: `有效期结束时间`, colKey: 'endDate', align: 'center', minWidth: 112, width: 180 },
  { title: `总数量`, colKey: 'totalQuantity', align: 'center' },
  { title: `剩余数量`, colKey: 'remainingQuantity', align: 'center' },
  { title: `使用说明`, colKey: 'description', align: 'center', ellipsis: true },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 180 },
  { title: `操作`, colKey: 'operation', align: 'center', width: 180 },
]);
// 提交表单对象
const form = ref<XyywCouponVo & XyywCouponForm>({});
// 查询对象
const queryParams = ref<XyywCouponQuery>({
  pageNum: 1,
  pageSize: 10,
  shopId: undefined,
  couponName: undefined,
  type: undefined,
  value: undefined,
  minSpend: undefined,
  startDate: undefined,
  endDate: undefined,
  totalQuantity: undefined,
  remainingQuantity: undefined,
  description: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询优惠券列表 */
function getList() {
  loading.value = true;
  listCoupon(queryParams.value)
    .then((response) => {
      couponList.value = response.rows;
      total.value = response.total;
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm('couponRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加优惠券';
}

/** 详情按钮操作 */
function handleDetail(row: XyywCouponVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const couponId = row.couponId;
  getCoupon(couponId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: XyywCouponVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改优惠券';
  const couponId = row?.couponId || ids.value.at(0);
  getCoupon(couponId).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.couponId) {
      updateCoupon(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addCoupon(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: XyywCouponVo) {
  const couponIds = row?.couponId || ids.value;
  proxy.$modal.confirm(`是否确认删除优惠券编号为${couponIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delCoupon(couponIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, couponIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'xyyw/coupon/export',
    {
      ...queryParams.value,
    },
    `coupon_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>
